package com.ruoyi.system.module.deptSynchron.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.*;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.system.api.domain.SysDept;

import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.domain.HeDepartment;
import com.ruoyi.system.domain.Qualification;
import com.ruoyi.system.hbos.domain.HbosDeptInput;
import com.ruoyi.system.hbos.tool.HbosDataUtils;

import com.ruoyi.system.module.deptSynchron.service.IDeptSyncService;
import com.ruoyi.system.service.IHeDepartmentService;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/wtc/dept")
public class DeptController extends BaseController {
    @Autowired
    private IDeptSyncService deptSyncService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IHeDepartmentService heDepartmentService;

    public List<String> deptName = Arrays.asList("临床", "后勤", "行政", "科研", "医疗", "教学", "其他");
    public List<Integer> tempIds = new ArrayList<>();

    // 将 JsonElement 转换为 List 对象
    private static <T> List<T> jsonElementToList(JsonElement jsonElement, Class<T> clazz) {
        List<T> list = new ArrayList<>();

        if (jsonElement.isJsonArray()) {
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            Gson gson = new Gson();

            for (JsonElement element : jsonArray) {
                T item = gson.fromJson(element, clazz);
                list.add(item);
            }
        }

        return list;
    }

    @PostMapping("/synchron")
    public void dataUpdates() {
        HbosDeptInput hbosDeptInput = new HbosDeptInput();
        hbosDeptInput.setCampusIds(Arrays.asList(30053002L));
        // 只查启用状态
        hbosDeptInput.setStatus(1);
        // 获取管理人邮箱（接口中的部门ID）
        List<String> emailList = deptSyncService.selectEmailList();

        // 不是病区
        hbosDeptInput.setInpatientArea(0);
        handleDept(hbosDeptInput, emailList);

        // 是病区
        hbosDeptInput.setInpatientArea(1);
        tempIds.clear();
        handleDept(hbosDeptInput, emailList);

        // 删除不存在的部门
        List<String> emailRegular = Arrays.asList("100", "113", "114", "115", "116", "117", "118", "119", "120", "121", "122", "123", "124", "125", "126", "127", "128", "129", "130");
        emailList.removeAll(emailRegular);
        if (emailList.size() > 0) {
            for (String email : emailList) {
                deptSyncService.deleteDeptByEmail(email);
            }
        }
    }

    // 请求并处理
    public void handleDept(HbosDeptInput hbosDeptInput, List<String> emailList) {
        HbosDataUtils utils = new HbosDataUtils();
        JSONObject json = utils.getHbosDept(hbosDeptInput);
        SysDictData dictData=new SysDictData();
        dictData.setDictType("he_department_name");
        dictData.setIsDefault("N");
        dictData.setStatus("0");
        dictData.setListClass("default");
        dictData.setCreateBy("admin");
        dictData.setCssClass(null);
        dictData.setCreateTime(DateUtils.getNowDate());

        SysDictData dictData1=new SysDictData();
        //dictData1.setDictType("he_department_name");
        dictData1.setIsDefault("N");
        dictData1.setStatus("0");
        dictData1.setListClass("default");
        dictData1.setCreateBy("admin");
        dictData1.setCssClass(null);
        dictData1.setCreateTime(DateUtils.getNowDate());

        if (!(json == null || json.equals(""))) {
            String code = json.getString("code");
            if (!(code == null || code.equals(""))) {
                if (code.equals("200")) {
                    //System.out.println(json.getJSONArray("data"));
                    //System.out.println(emailList);
                    JSONArray dataArray = json.getJSONArray("data");
                    sortArray(dataArray);
                    for (int i = 0; i < dataArray.size(); i++) {
                        //System.out.println(dataArray.get(i)+"");
                        JsonParser jsonParser = new JsonParser();
                        JsonObject dataJson = jsonParser.parse(dataArray.get(i) + "").getAsJsonObject();
                        //String deptName = dataJson.get("deptName").getAsString();
                        String deptId = dataJson.get("deptId").getAsLong() + "";
                        //System.out.println(deptName + deptId);
                        //System.out.println(dataJson.get("deptName").getAsString());
                        if (!emailList.contains(deptId)) {
                            SysDept dept = new SysDept();
                            dept.setDeptName(dataJson.get("deptName").getAsString());
                            dept.setEmail(deptId);

                            if (dataJson.get("parentBusinessDeptId") != null) {
                                Long selectId = deptSyncService.selectIdByEmail(dataJson.get("parentBusinessDeptId").getAsString());
                                //System.out.println(selectId);
                                if (selectId == null) {
                                    //if (dataJson.get("deptTypeName") != null) {
                                    //    //System.out.println(dataJson.get("deptTypeName").getAsString());
                                    //    dept.setParentId(110L + deptName.indexOf(dataJson.get("deptTypeName").getAsString()));
                                    //} else {
                                    //    dept.setParentId(100L);
                                    //}
                                    tempIds.add(i);
                                    continue;
                                } else {
                                    dept.setParentId(selectId);
                                }
                            } else {
                                if (dataJson.get("deptTypeName") != null) {
                                    //System.out.println(dataJson.get("deptTypeName").getAsString());
                                    dept.setParentId(124L + deptName.indexOf(dataJson.get("deptTypeName").getAsString()));
                                } else {
                                    dept.setParentId(100L);
                                }
                            }

                            if(dataJson.get("serviceScopes") != null){
                                JsonElement jsonElement=dataJson.get("serviceScopes");
                                List<String> qualifications = jsonElementToList(jsonElement, String.class);
                                if(qualifications.size()>0){
                                    if(qualifications.get(qualifications.size()-1).equals("emergency")){
                                        dictData1.setDictType("he_emergency_department");
                                        if(dataJson.get("deptName")!=null&&dataJson.get("deptId")!=null){
                                            dictData1.setDictLabel(dataJson.get("deptName").toString());
                                            dictData1.setDictValue(dataJson.get("deptId").toString());
                                            dictDataService.insertDictData(dictData1);
                                        }

                                    }else if(qualifications.get(qualifications.size()-1).equals("observation")){
                                        dictData1.setDictType("he_observation_department");
                                        if(dataJson.get("deptName")!=null&&dataJson.get("deptId")!=null){
                                            dictData1.setDictLabel(dataJson.get("deptName").toString());
                                            dictData1.setDictValue(dataJson.get("deptId").toString());
                                            dictDataService.insertDictData(dictData1);
                                        }

                                    }else if(qualifications.get(qualifications.size()-1).equals("rescue")){
                                        dictData1.setDictType("he_rescue_department");
                                        if(dataJson.get("deptName")!=null&&dataJson.get("deptId")!=null){
                                            dictData1.setDictLabel(dataJson.get("deptName").toString());
                                            dictData1.setDictValue(dataJson.get("deptId").toString());
                                            dictDataService.insertDictData(dictData1);
                                        }

                                    }
                                }


                            }
                            deptSyncService.insertDeptNew(dept);
                            dictData.setDictLabel(dept.getDeptName());
                            dictData.setDictValue(dept.getDeptId().toString());
                            dictDataService.insertDictData(dictData);
                            HeDepartment heDepartment=new HeDepartment();
                            heDepartment.setDepartmentName(dept.getDeptName());
                            heDepartment.setDepartmentNumber(dept.getDeptId().toString());
                            heDepartmentService.insertHeDepartment(heDepartment);
                        } else {
                            emailList.remove(deptId);
                        }
                    }
                    if (tempIds.size() > 0) {
                        for (Integer idx : tempIds) {
                            JsonParser jsonParser = new JsonParser();
                            JsonObject dataJson = jsonParser.parse(dataArray.get(idx) + "").getAsJsonObject();
                            String deptId = dataJson.get("deptId").getAsLong() + "";

                            SysDept dept = new SysDept();
                            dept.setDeptName(dataJson.get("deptName").getAsString());
                            dept.setEmail(deptId);

                            Long selectId = deptSyncService.selectIdByEmail(dataJson.get("parentBusinessDeptId").getAsString());
                            if (selectId == null) {
                                if (dataJson.get("deptTypeName") != null) {
                                    dept.setParentId(124L + deptName.indexOf(dataJson.get("deptTypeName").getAsString()));
                                } else {
                                    dept.setParentId(100L);
                                }
                            } else {
                                dept.setParentId(selectId);
                            }
                            if(dataJson.get("serviceScopes") != null){
                                JsonElement jsonElement=dataJson.get("serviceScopes");
                                List<String> qualifications = jsonElementToList(jsonElement, String.class);
                                if(qualifications.size()>0){
                                    if(qualifications.get(qualifications.size()-1).equals("emergency")){
                                        dictData1.setDictType("he_emergency_department");
                                        if(dataJson.get("deptName")!=null&&dataJson.get("deptId")!=null){
                                            dictData1.setDictLabel(dataJson.get("deptName").toString());
                                            dictData1.setDictValue(dataJson.get("deptId").toString());
                                            dictDataService.insertDictData(dictData1);
                                        }

                                    }else if(qualifications.get(qualifications.size()-1).equals("observation")){
                                        dictData1.setDictType("he_observation_department");
                                        if(dataJson.get("deptName")!=null&&dataJson.get("deptId")!=null){
                                            dictData1.setDictLabel(dataJson.get("deptName").toString());
                                            dictData1.setDictValue(dataJson.get("deptId").toString());
                                            dictDataService.insertDictData(dictData1);
                                        }

                                    }else if(qualifications.get(qualifications.size()-1).equals("rescue")){
                                        dictData1.setDictType("he_rescue_department");
                                        if(dataJson.get("deptName")!=null&&dataJson.get("deptId")!=null){
                                            dictData1.setDictLabel(dataJson.get("deptName").toString());
                                            dictData1.setDictValue(dataJson.get("deptId").toString());
                                            dictDataService.insertDictData(dictData1);
                                        }

                                    }
                                }


                            }
                            deptSyncService.insertDeptNew(dept);
                            dictData.setDictLabel(dept.getDeptName());
                            dictData.setDictValue(dept.getDeptId().toString());
                            dictDataService.insertDictData(dictData);
                            HeDepartment heDepartment=new HeDepartment();
                            heDepartment.setDepartmentName(dept.getDeptName());
                            heDepartment.setDepartmentNumber(dept.getDeptId().toString());
                            heDepartmentService.insertHeDepartment(heDepartment);
                        }
                    }
                } else {
                    System.out.println("请求错误：" + json);
                }
            }
        }
    }

    // 排序
    public void sortArray(JSONArray dataArray) {
        dataArray.sort((obj1, obj2) -> {
            JsonParser jsonParser = new JsonParser();
            JsonObject dataJson1 = jsonParser.parse(obj1 + "").getAsJsonObject();
            JsonObject dataJson2 = jsonParser.parse(obj2 + "").getAsJsonObject();

            boolean isNull1 = dataJson1.get("parentBusinessDeptId") == null;
            boolean isNull2 = dataJson2.get("parentBusinessDeptId") == null;

            if (isNull1 && !isNull2) {
                return -1;
            } else if (!isNull1 && isNull2) {
                return 1;
            }

            return Long.compare(dataJson1.get("deptId").getAsLong(), dataJson2.get("deptId").getAsLong());
        });
    }

    public static void main(String[] args) {
        HbosDeptInput hbosDeptInput = new HbosDeptInput();
        // 只查启用状态
        hbosDeptInput.setStatus(1);
        hbosDeptInput.setInpatientArea(0);
        HbosDataUtils utils = new HbosDataUtils();
        JSONObject json = utils.getHbosDept(hbosDeptInput);

        if (!(json == null || json.equals(""))) {
            String code = json.getString("code");
            if (!(code == null || code.equals(""))) {
                if (code.equals("200")) {
                    //System.out.println(json.getJSONArray("data"));
                    //System.out.println(emailList);
                    JSONArray dataArray = json.getJSONArray("data");
                    //dataArray.sort(Comparator.comparing(obj->{
                    //    JsonParser jsonParser = new JsonParser();
                    //    JsonObject dataJson = jsonParser.parse(obj + "").getAsJsonObject();
                    //    int parentBusinessDeptIdValue = dataJson.get("parentBusinessDeptId") == null ? 0 : 1;
                    //    return new Object[]{parentBusinessDeptIdValue, dataJson.get("deptId").getAsInt()};
                    //}));

                    dataArray.sort((obj1, obj2) -> {
                        JsonParser jsonParser = new JsonParser();
                        JsonObject dataJson1 = jsonParser.parse(obj1 + "").getAsJsonObject();
                        JsonObject dataJson2 = jsonParser.parse(obj2 + "").getAsJsonObject();

                        boolean isNull1 = dataJson1.get("parentBusinessDeptId") == null;
                        boolean isNull2 = dataJson2.get("parentBusinessDeptId") == null;

                        if (isNull1 && !isNull2) {
                            return -1;
                        } else if (!isNull1 && isNull2) {
                            return 1;
                        }

                        return Long.compare(dataJson1.get("deptId").getAsLong(), dataJson2.get("deptId").getAsLong());
                    });

                    //System.out.println(dataArray);
                    for (Object o : dataArray) {
                        JsonParser jsonParser = new JsonParser();
                        JsonObject dataJson = jsonParser.parse(o + "").getAsJsonObject();
                        System.out.println(dataJson);
                    }
                }
            }
        }
    }
}
